<?php

namespace App\Http\Controllers\Api;

use App\Model\AsdModel;
use App\Model\HomeTotalModel;
use App\Model\NoticeModel;
use App\Model\BannerModel;
use App\Model\SearchModel;
use App\Model\SearchLogModel;
use App\Model\ShopBrandModel;
use App\Model\ShopGoodModel;
use App\model\ShopGoodType;
use App\Model\ShopLabelModel;
use App\Model\ShopTypeModel;
use App\Model\ShopHomeModel;
use App\Model\StoreGoodModel;
use App\Model\SkuModel;
use App\Model\ShopCartModel;
use App\Model\ShopOrderFsModel;
use App\Model\ShopOrderFstModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class HomeController extends Controller
{
	//首页接口
	public function index(){
		//商品banner
		$data['banner'] = BannerModel::doList();
		//首页类型
		$data['home'] = ShopHomeModel::doList();
		//公告
		$data['notice'] = NoticeModel::doList();
		//统计
		$data['total'] = HomeTotalModel::doList();
		//推荐专区
		$data['is_sell'] = ShopGoodModel::getSell();
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//商品分类
	public function type(){
		//商品类型
		$data['list'] = ShopTypeModel::where('display',1)->select('id','name','tid')->orderBy('sort','desc')->get();
		foreach($data['list'] as $k=>$v){
			$data['list'][$k]['id'] = $v['tid'];
		}

		return ['code'=>1,'msg'=>'返回商品分类','data'=>$data];
	}

	//商品
	public function glist(){
		//总销量前10
		$data['sell'] = ShopOrderFsModel::shop(1);
		$data['b_sell'] = ShopOrderFsModel::shop(2);
		$data['store'] = ShopOrderFsModel::shop(3);
		$data['b_store'] = ShopOrderFsModel::shop(4);
		return ['code'=>1,'msg'=>'返回商品信息','data'=>$data];

	}

//	==============================================类型==================================================================
	//类型商品
	public function type_goods(){
//		if(!request()->typeid){
//			return ['code'=>0,'msg'=>retStrInfo(76)];
//		}
		$arr = [];
		$data = [];

		$list = ShopGoodModel::where(function ($query) {
			if (request()->typeid) {
				//查询子类
				$son_type = ShopTypeModel::where('pid',request()->typeid)->get();
				$type =request()->typeid.",";
				foreach($son_type as $k=>$v){
					$type .= $v['tid'].",";
				}
				$type = explode(',',trim($type,','));
				$ids = DB::table('shop_good_type')->distinct(true)->whereIn('tid',$type)->pluck('gid');
				$query->whereIn('id', $ids);
			}
		})->where('state',1)->OrderBy('created_at','desc')->paginate(30);
		if($list){
			foreach($list as $k=>$v){
				$data[$k]['id'] = $v['id'];
				$data[$k]['name'] = $v['name'];
				if($v['title']){
					$data[$k]['name'] = $v['title'];
				}
				$data[$k]['sell_price'] = number_format($v['sell_price'],2,".","");
				$data[$k]['picname'] = "http://".$_SERVER['HTTP_HOST'].$v['picpath'].$v['picname'];
				if($v['oss_pic']){
					$data[$k]['picname'] = $v['oss_pic'];
				}
				$data[$k]['store_num'] = StoreGoodModel::where('gid',$v['id'])->sum('num');
				$data[$k]['sell_num'] = $v['sale_num'];

				$label_res = [];
				$label = explode(',',$v['labels']);
				foreach($label as $key=>$val){
					$label_info = ShopLabelModel::where('id',$val)->first();
					if($label_info){
						$label_res[] = $label_info['color'];
					}
				}
				$data[$k]['label'] = array_values($label_res);
				//专柜价
				$data[$k]['del_coin'] = $v['del_coin'];
			}
		}
		$arr['list'] = $data;
		return ['code'=>'1','msg'=>'返回数据','data'=>$arr];

	}


//	===============================================筛选(获取一级分类)============================================================
	public function search_type(){
		$arr = [];
		if(!request()->tid){
			$list = ShopTypeModel::where('level',0)->orderBy('sort','desc')->get();
		}else{
			$list = ShopTypeModel::where('pid',request()->tid)->orderBy('sort','desc')->get();
		}
		foreach($list as $k=>$v){
			$arr[$k]['id'] = $v['tid'];
			$arr[$k]['name'] = $v['name'];
		}
		$data['list'] = $arr;
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//品牌
	public function search_brand(Request $request){
		$tid = $request->input('tid',1);

		$data['list'] = [];
		$ids = DB::table('shop_good_type')->distinct(true)->where('tid',$tid)->pluck('gid');

		$list = ShopGoodModel::whereIn('id',$ids)->where('state',1)->where('bid','<>',0)->get();
		if(count($list) > 0){
			$arr = '';
			foreach($list as $k=>$v){
				$arr .= $v['bid'].",";
			}
			$arr = rtrim($arr,",");
			$arr = explode(',',$arr);
			$arr_cy = array_unique($arr);

			$brand = [];
			$data = [];
			foreach($arr_cy as $k=>$v){
				$brand_list = ShopBrandModel::where('bid',$v)->first();
				$brand[$k]['name'] = $brand_list['name'];
				$brand[$k]['id'] = $brand_list['bid'];
			}
			$data['list'] = array_values($brand);
		}

		return ['code'=>1,'msg'=>'返回品牌','data'=>$data];

	}

	//标签
	public function search_label(){
		$list = ShopLabelModel::where('state',1)->select('id','name')->get();
		$data['list'] = $list;
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//筛选
	public function search(){
		$data = [];
		if(!request()->status){
			request()->status = 1;
		}
		if(request()->keywords){
			SearchModel::do_add(request()->header('uid'),request()->keywords);
		}
		switch(request()->status){
			case '1':
				//商品
				$list = ShopGoodModel::where(function ($query) {
					if (request()->tid) {
						//查询子类
						$son_type = ShopTypeModel::where('pid',request()->tid)->get();
						$type =request()->tid.",";
						foreach($son_type as $k=>$v){
							$type .= $v['tid'].",";
						}
						$type = explode(',',trim($type,','));

						$ids = DB::table('shop_good_type')->distinct(true)->whereIn('tid',$type)->pluck('gid');
						$query->whereIn('id', $ids);
					}
					if (request()->bid) {
						$query->where('bid', request()->bid);
					}
					if (request()->label) {
						$query->where('labels',"like","%,".request()->label.",%");
					}
					if(request()->keywords){
						$query->where('title', "like" , "%".request()->keywords."%");
					}
				})->where('state',1)
//				->orderBy('created_at','desc')
					->orderBy('created_at','asc')

					->select('id','name','picname','picpath','tid','bid','labels','sell_price','sale_num','title','oss_pic')->paginate(30);
	
				break;
			case '2':
				//商品
				$list = ShopGoodModel::where(function ($query) {
					if (request()->tid) {
						//查询子类
						$son_type = ShopTypeModel::where('pid',request()->tid)->get();
						$type =request()->tid.",";
						foreach($son_type as $k=>$v){
							$type .= $v['tid'].",";
						}
						$type = explode(',',trim($type,','));
//						$query->whereIn('tid', $type);
						$ids = DB::table('shop_good_type')->distinct(true)->whereIn('tid',$type)->pluck('gid');
						$query->whereIn('id', $ids);
					}
					if (request()->bid) {
						$query->where('bid', request()->bid);
					}
					if (request()->label) {
						$query->where('labels',"like","%,".request()->label.",%");
					}
					if(request()->keywords){
						$query->where('title', "like" , "%".request()->keywords."%");
					}
				})->where('state',1)
					->orderBy('sale_num','desc')
					->select('id','name','picname','picpath','tid','bid','labels','sell_price','sale_num','title','oss_pic')->paginate(30);
				break;
			case '3':
				//商品
				$list = ShopGoodModel::where(function ($query) {
					if (request()->tid) {
						//查询子类
						$son_type = ShopTypeModel::where('pid',request()->tid)->get();
						$type =request()->tid.",";
						foreach($son_type as $k=>$v){
							$type .= $v['tid'].",";
						}
						$type = explode(',',trim($type,','));
//						$query->whereIn('tid', $type);
						$ids = DB::table('shop_good_type')->distinct(true)->whereIn('tid',$type)->pluck('gid');
						$query->whereIn('id', $ids);
					}
					if (request()->bid) {
						$query->where('bid', request()->bid);
					}
					if (request()->label) {
						$query->where('labels',"like","%,".request()->label.",%");
					}
					if(request()->keywords){
						$query->where('title', "like" , "%".request()->keywords."%");
					}
				})->where('state',1)
				->orderBy('sell_price','desc')
				->select('id','name','picname','picpath','tid','bid','labels','sell_price','sale_num','title','oss_pic')->paginate(30);

				break;
			case '4':
				//商品
				$list = ShopGoodModel::where(function ($query) {
					if (request()->tid) {
						//查询子类
						$son_type = ShopTypeModel::where('pid',request()->tid)->get();
						$type =request()->tid.",";
						foreach($son_type as $k=>$v){
							$type .= $v['tid'].",";
						}
						$type = explode(',',trim($type,','));
//						$query->whereIn('tid', $type);
						$ids = DB::table('shop_good_type')->distinct(true)->whereIn('tid',$type)->pluck('gid');
						$query->whereIn('id', $ids);
					}
					if (request()->bid) {
						$query->where('bid', request()->bid);
					}
					if (request()->label) {
						$query->where('labels',"like","%,".request()->label.",%");
					}
					if(request()->keywords){
						$query->where('title', "like" , "%".request()->keywords."%");
					}
				})->where('state',1)
				->orderBy('sell_price','asc')
				->select('id','name','picname','picpath','tid','bid','labels','sell_price','sale_num','title','oss_pic')->paginate(30);
				break;
		}

		foreach($list as $k=>$v){
			
			$data[$k]['id'] = $v['id'];
			$data[$k]['name'] = $v['name'];
			if($v['title']){
				$data[$k]['name'] = $v['title'];
			}
			$data[$k]['picname'] = "http://".$_SERVER['HTTP_HOST'].$v['picpath'].$v['picname'];
			if($v['oss_pic']){
				$data[$k]['picname'] = $v['oss_pic'];
			}
			$data[$k]['sell_price'] = number_format($v['sell_price'],2,".","");
			$data[$k]['store_num'] = StoreGoodModel::where('gid',$v['id'])->sum('num');
			$data[$k]['sale_num'] = $v['sale_num'];

			$label_res = [];
			$label = explode(',',$v['labels']);
			foreach($label as $key=>$val){
				$label_info = ShopLabelModel::where('id',$val)->first();
				if($label_info){
					$label_res[] = $label_info['color'];
				}
			}
			$data[$k]['label'] = array_values($label_res);
			
			//商品信息
			$good_res = ShopGoodModel::where('id',$v['id'])->first();
			//专柜价
			$data[$k]['del_coin'] = $good_res['del_coin'];
		}

		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//更多商品
	public function more_good(Request $request){
		$type = $request->input('type',1);
		$list = [];
		switch($type){
			case '1':
				$list = ShopOrderFsModel::shop(5);
				break;
			case '2':
				$list = ShopOrderFsModel::shop(6);
				break;
			case '3':
				$list = ShopOrderFsModel::shop(7);
				break;
			case '4':
				$list = ShopOrderFsModel::shop(8);
				break;
		}
		return ['code'=>1,'msg'=>'返回数据','data'=>$list];
	}

	//商品类型列表
	public function type_good(Request $request){
		$type = $request->input('type',1);
		$status = $request->input('status',1);
		$data = [];
		switch($type){
			case '1':
				//综合
				if($status == 1){
					$data['list'] = ShopOrderFsModel::shop(9);
				//销量
				}elseif($status == 2){
					$data['list'] = ShopOrderFsModel::shop(11);
				//价格从低到高
				}elseif($status == 3){
					$data['list'] = ShopOrderFsModel::shop(12);
				//价格从高到低
				}elseif($status == 4){
					$data['list'] = ShopOrderFsModel::shop(13);
				}
				return ['code'=>1,'msg'=>'返回数据','data'=>$data];
				break;
			case '2':
				$data['hot'] = [];
				//爆款
				$is_hot = ShopLabelModel::where('name','爆款')->value('id');
				$list = ShopGoodModel::where('labels','like',"%,".$is_hot.",%")->select('id','name','picpath','picname','sell_price','title','labels','oss_pic')->where('state',1)->orderBy('sale_num','desc')->limit(3)->get();
				if(count($list) > 0){
					foreach($list as $k=>$v){
						$v['picname'] = "http://".$_SERVER['HTTP_HOST'].$v['picpath'].$v['picname'];
						if($v['oss_pic']){
							$v['picname'] = $v['oss_pic'];
						}
						$v['sell_price'] = number_format($v['sell_price'],2,".","");
						if($v['title']){
							$v['name'] = $v['title'];
						}

						$label_res = [];
						$label = explode(',',$v['labels']);
						foreach($label as $key=>$val){
							$label_info = ShopLabelModel::where('id',$val)->first();
							if($label_info){
								$label_res[] = $label_info['color'];
							}
						}
						$v['label'] = array_values($label_res);
						//商品信息
						$good_res = ShopGoodModel::where('id',$v['id'])->first();
						//专柜价
						$v['del_coin'] = $good_res['del_coin'];
					}
					$data['hot'] = $list;
				}

				//特卖
				$data['list'] = ShopOrderFsModel::shop(10);
				return ['code'=>1,'msg'=>'返回数据','data'=>$data];
				break;
		}
	}

	//品牌
	public function brand(){
		$szm = array('A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','W','X','Y','Z');
		$data['szm'] = $szm;//首字母
		$keywords = request()->keywords;
		//直推下级信息
		$data['brand'] = ShopBrandModel::letter($keywords);
		$data['brand_cy'] = ShopBrandModel::getList($keywords);


		return ['code'=>1,'msg'=>'','data'=>$data];
	}

	//联系方式
	public function linktel(){
		$arr_tel = AsdModel::where('type',1)->select('id','phone')->get();
		$arr_qrc = AsdModel::where('type',2)->select('id','phone','qrcode')->get();
		foreach ($arr_qrc as $k=>$v){
			$arr_qrc[$k]['qrcode'] = "http://".$_SERVER['HTTP_HOST'].$v['qrcode'];
		}
		$data['arr_tel'] = $arr_tel;
		$data['arr_qrc'] = $arr_qrc;
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//搜索
	public function globle(){
		$data = [];
		$list = ShopGoodModel::where('name','like',"%".request()->keywords."%")->select('id','picname','picpath','name','sale_num','sell_price','title','oss_pic')->where('state',1)->get();

		foreach($list as $k=>$v){
			$data[$k]['id'] = $v['id'];
			$data[$k]['name'] = $v['name'];
			if($v['title']){
				$data[$k]['name'] = $v['title'];
			}
			$data[$k]['picname'] = "http://".$_SERVER['HTTP_HOST'].$v['picpath'].$v['picname'];
			if($v['oss_pic']){
				$data[$k]['picname'] = $v['oss_pic'];
			}
			//销售价
			$data[$k]['single_price'] = number_format($v['sell_price'],2,".","");
			//入库量
			$data[$k]['store_num'] = StoreGoodModel::where('gid',$v['id'])->sum('num');
			//销量
			$data[$k]['sell_num'] = $v['sale_num'];
		}
		SearchModel::do_add(request()->header('uid'),request()->keywords);

		return ['code'=>1,'msg'=>'返回数据','data'=>$data];

	}

	//搜索关键字
	public function search_key(){
		$user['keywords'] = [];
		if(request()->header('uid')){
			$user['keywords'] = SearchModel::where('uid',request()->header('uid'))->select('id','name')->get();
		}
		$user['search_log'] = SearchLogModel::orderBy('id','desc')->select('id','name')->get();
		return ['code'=>1,'msg'=>'返回数据','data'=>$user];
	}

	//搜索品牌
	public function globle_brand(Request $request){
		$data = [];
		$keywords = $request->input('keywords','');
		$list = ShopBrandModel::where('name','like',"%".$keywords."%")->get();
		foreach($list as $k=>$v){
			$data[$k]['id'] = $v['bid'];
			$data[$k]['name'] = $v['name'];
			$data[$k]['picname'] = 'http://'.$_SERVER['HTTP_HOST'].$v['picpath'].$v['picname'];


		}


		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//删除搜索记录
	public function search_del(){
		if(request()->header('uid')){
			DB::beginTransaction();
			try{
				SearchModel::where('uid',request()->header('uid'))->delete();
				DB::commit();
				return ['code'=>'1','msg'=>retStrInfo(72)];
			}catch(Exception $e){
				DB::rollBack();
				return ['code'=>'0','msg'=>retStrInfo(73)];
			}
		}else{
			return ['code'=>1,'msg'=>''];
		}
	}

	//为你推荐为你推荐
	public function commend(Request $request){
		$data = [];
		if(request()->header('uid')){
			$page = $request->input('page',0);
			$start = $page*10+1;
			$keywords = SearchModel::where('uid',request()->header('uid'))->orderBy('id','desc')->get();
			if(count($keywords)>0){
			
				$list = [];
				$keys = 0;
				foreach($keywords as $k=>$v){
					$lists = ShopGoodModel::where('name','like',"%".$v['name']."%")->where('state',1)->get();
					foreach($lists as $key=>$val){
						$list[$keys]['id'] = $val['id'];
						$list[$keys]['name'] = $val['name'];
						$list[$keys]['picname'] = $val['picname'];
						$list[$keys]['picpath'] = $val['picpath'];
						$list[$keys]['oss_pic'] = $val['oss_pic'];
						$list[$keys]['sell_price'] = $val['sell_price'];
						$list[$keys]['store_num'] = $val['store_num'];
						$list[$keys]['sale_num'] = $val['sale_num'];
						$list[$keys]['labels'] = $val['labels'];
						$list[$keys]['title'] = $val['title'];
						$list[$keys]['num'] = $val['num'];
						$list[$keys]['is_attr'] = $val['is_attr'];
						$list[$keys]['del_coin'] = $val['del_coin'];
						$keys += 1;
					}
				}
				$list = array_slice($list,$start,10);
				array_values($list);
				if(count($list) <= 0){
					$list = ShopGoodModel::OrderBy('created_at','desc')->where('state',1)->paginate(30);
				}
			}else{
				$list = ShopGoodModel::OrderBy('created_at','desc')->where('state',1)->paginate(30);
			}
		}else{
			$list = ShopGoodModel::OrderBy('created_at','desc')->where('state',1)->paginate(30);
		}
		foreach($list as $k=>$v){
			$data[$k]['id'] = $v['id'];
			$data[$k]['name'] = $v['name'];
			if($v['title']){
				$data[$k]['name'] = $v['title'];
			}
			$data[$k]['picname'] = "http://".$_SERVER['HTTP_HOST'].$v['picpath'].$v['picname'];
			if($v['oss_pic']){
				$data[$k]['picname'] = $v['oss_pic'];
			}
			$data[$k]['sell_price'] = number_format($v['sell_price'],2,".","");
			$data[$k]['store_num'] = $v['num'];
			if($v['is_attr'] == 1){
				$data[$k]['store_num'] = SkuModel::where('gid',$v['id'])->sum('sum');
			}
			$data[$k]['sell_num'] = $v['sale_num'];

			$label_res = [];
			$label = explode(',',$v['labels']);
			foreach($label as $key=>$val){
				$label_info = ShopLabelModel::where('id',$val)->first();
				if($label_info){
					$label_res[] = $label_info['color'];
				}
			}
			$data[$k]['label'] = array_values($label_res);
			$data[$k]['del_coin'] = $v['del_coin'];

			$data[$k]['is_cart'] = 2;
			if(ShopCartModel::where('gid',$v['id'])->where('uid',request()->header('uid'))->first()){
				$data[$k]['is_cart'] = 1;
			}

		}
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//公告详情
	public function n_detail(){
		if(!request()->id){
			return ['code'=>0,'msg'=>retStrInfo(112)];
		}
		$list = NoticeModel::where('id',request()->id)->select('title','created_at','content')->first();
		if(!$list){
			return ['code'=>0,'msg'=>retStrInfo(113)];
		}
		$list['addtime'] = substr($list['created_at'],0,10);
		$list['content'] = str_replace('/upload','http://'.$_SERVER['HTTP_HOST'].'/upload',$list['content']);
		$list['content'] = str_replace("table width=\"790\"","table width=\"100%\"",$list['content']);
		$list['content'] = str_replace("<img ","<img style='width:100%' ",$list['content']);
		$data['list'] = $list;
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//公告列表
	public function notice_list(){
		$list = NoticeModel::where('state',1)->orderBy('sort','desc')->select('id','title','content','created_at','desc')->get();
		foreach($list as $k=>$v){
			$v['addtime'] = substr($v['created_at'],6,10);
			$v['content'] = str_replace('/upload','http://'.$_SERVER['HTTP_HOST'].'/upload',$v['content']);
			$v['content'] = str_replace("table width=\"790\"","table width=\"100%\"",$v['content']);
			$v['content'] = str_replace("<img ","<img style='width:100%' ",$v['content']);
		}
		$data['list'] = $list;
		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}



}